// LoginScreen.tsx
import { Stack } from 'expo-router';
import React, { useState } from 'react';
import { Alert, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import Toast from 'react-native-toast-message';
import { userApi } from '../services/user_api';
import { setUserTokenData } from '../utils/storage';

export default function LoginScreen() {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [codeSent, setCodeSent] = useState(false);
  const [timer, setTimer] = useState(0);

  // 模拟发送验证码
  const sendCode = () => {
    if (!/^\d{10,15}$/.test(phone)) {
      Toast.show({ type: 'error', text1: '请输入有效手机号！' });
      return;
    }
    setCodeSent(true);
    setTimer(60); // 60秒倒计时

    const interval = setInterval(() => {
      setTimer((prev) => {
        if (prev <= 1) {
          clearInterval(interval);
          setCodeSent(false);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    Alert.alert('验证码已发送', `验证码已发送到 ${phone}（此处仅模拟）`);
  };

  const login = async () => {

    if (!phone || !code) {
       Toast.show({ type: 'success', text1: '请输入手机号和验证码' });
      // Alert.alert('提示', '请输入手机号和验证码');
      return;
    }
    try {
      const login = await userApi.login({ mobile: phone, password: code });
      await setUserTokenData(login)
      Toast.show({ type: 'success', text1: '登录成功！' });
    } catch (error: any) {
      Toast.show({ type: 'error', text1: '登录失败', text2: error.message });
    }
  };

  return (
    <View style={styles.container}>
      <Stack.Screen options={{ headerShown: false }} /> {/* ✅ 隐藏标题栏 */}
      <Text style={styles.title}>手机号登录</Text>
      <TextInput
        style={styles.input}
        placeholder="请输入手机号"
        keyboardType="phone-pad"
        value={phone}
        onChangeText={setPhone}
      />
      <View style={styles.codeRow}>
        <TextInput
          style={[styles.input, { flex: 1 }]}
          placeholder="请输入验证码"
          keyboardType="number-pad"
          value={code}
          onChangeText={setCode}
        />
        <TouchableOpacity
          style={[styles.codeButton, codeSent ? styles.codeButtonDisabled : {}]}
          disabled={codeSent}
          onPress={sendCode}
        >
          <Text style={styles.codeButtonText}>
            {codeSent ? `重新发送 (${timer})` : '获取验证码'}
          </Text>
        </TouchableOpacity>
      </View>
      <TouchableOpacity style={styles.loginButton} onPress={login}>
        <Text style={styles.loginButtonText}>登录</Text>
      </TouchableOpacity>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 80,
    backgroundColor: '#f2f2f2',
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    marginBottom: 40,
    textAlign: 'center',
  },
  input: {
    height: 50,
    backgroundColor: '#fff',
    borderRadius: 8,
    paddingHorizontal: 15,
    fontSize: 16,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  codeRow: {
    flexDirection: 'row',
  },
  codeButton: {
    marginLeft: 10,
    paddingHorizontal: 15,
    height: 50,
    backgroundColor: '#1E90FF',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
  },
  codeButtonDisabled: {
    backgroundColor: '#aaa',
  },
  codeButtonText: {
    color: '#fff',
    fontSize: 16,
  },
  loginButton: {
    marginTop: 30,
    height: 50,
    backgroundColor: '#28a745',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
  },
  loginButtonText: {
    color: '#fff',
    fontSize: 18,
  },
});